// pages/cart/cart.js
import { async } from '../../lib/runtime/runtime'
import { request } from '../../request/index';
import { requestpayment } from '../../utils/pay'
Page({
  data: {
    address: {},//本地存储中地址值
    cart: [],//本地存储中的商品信息数据
    allchecked: true,//全选按钮的状态
    totalprice: 0,//总价格
    totalnum: 0//总数量

  },
  //onShow：页面显示或从后台跳回小程序时显示此页面时触发，从跳转页面返回时触发，不能传递参数
  onShow() {
    const address = wx.getStorageSync('address');
    const cart = wx.getStorageSync('cart');
    //const allchecked = cart.every(v => v.ischecked)
    //every是一个数组方法,会遍历数组,会接受一个回调函数,那么, 每一个回调函数都返回true 那么every方法的返回值为true
    //只要有一个回调函数返回了false 那么不在循环执行,则直接返回false
    this.setCart(cart)//调用setCart方法
    this.setData({
      address
    })
  },

  //设置复选框状态，重新计算 总价格 和总数量 和全选框状态
  setCart(cart) {
    let totalprice = 0
    let totalnum = 0
    let allchecked = true
    cart.forEach(v => {
      if (v.ischecked) {
        totalprice = v.goods_price * v.num
        totalnum = v.num
      } else {
        allchecked = false
        totalnum = 0
        totalprice = 0
      }
    })
    //判断数组是否为空
    allchecked = cart.length != 0 ? allchecked : false
    this.setData({
      cart,
      totalprice,
      totalnum,
      allchecked: allchecked
    })
  },

  //支付
  //微信支付
  //1哪些人可以实现微信支付
  //1企业账号
  //2企业的小程序后台中 必须给开发者添加上白名单
  //一个Appid可以绑定多个开发者账号
  async handletoken() {
    try {
      /* const token = wx.getStorageSync('token');
       if (!token) {
         wx.navigateTo({
           url: '/pages/auth/auth',
         });
       }*/
      //创建订单

      const token = { data: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo" }
      wx.setStorageSync('token', token);
      const header = { Authorization: token.data }
      const order_price = this.data.totalprice
      const consignee_addr = this.data.address.all
      let goods = [];
      const cart = this.data.cart.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_number: v.num,
        goods_price: v.goods_price
      }))
      const reqbody = { order_price, consignee_addr, goods }//请求体参数
      //准备发送请求
      const res = await request({ url: 'my/orders/create', data: reqbody, header: header, method: 'post' })
      console.log('创建订单返回参数' + res.order_number)
      //发起预支付的请求
      const { order_number } = res//获取订单编号
      const { pay } = await request({ url: 'my/orders/req_unifiedorder', data: order_number, header: header, method: 'post' })
      console.log('预支付返回参数' + pay)
      //发起微信支付
      // await requestpayment(pay)
      //查询订单
      const res3 = await request({ url: 'my/orders/chkOrder', data: order_number, header, method: 'post' })
      //过滤出未被选中的商品，重新添加进缓存
      let newcart = wx.getStorageSync('cart');
      newcart = newcart.filter(v => !v.ischecked)
      wx.setStorageSync('cart', newcart);
      await wx.showToast({
        title: '支付成功',
        icon: 'success',

      });
      wx.navigateTo({
        url: '/pages/order/order',
      });
    } catch (error) {
      await wx.showToast({
        title: '支付失败',
        icon: '',

      });
    }

  }



})